﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UniRx;

namespace NetFrame
{
    public class HttpConnect : MonoBehaviour
    {
        private static HttpConnect instance;
        public static HttpConnect GetInstance()
        {
            return instance;
        }

        public delegate void HttpRespDelegate(HttpResponse resp);
        public HttpRespDelegate HttpRespEvent;

        /// <summary>
        /// Http服务器URL
        /// </summary>
        private string url;

        void Awake()
        {
            instance = this;
            DontDestroyOnLoad(this);
            ConnectConfig.GetConnectConfig();
            url = "http://" + ConnectConfig.http_server_ip + ":" + ConnectConfig.http_server_port;
        }

        /// <summary>
        /// 开启Http请求的协程
        /// </summary>
        /// <param name="httpProtocol">请求的ID</param>
        /// <param name="post">用来存放发送给服务的参数</param>
        public void SendHttpResquest(WWWForm post, bool isReturn)
        {
            ObservableWWW.Post(url, post)
                .Where(_ => isReturn)
                .Subscribe(respText => {
                    HttpResponse resp = new HttpResponse(respText);
                    if (HttpRespEvent != null)
                    {
                        HttpRespEvent(resp);
                    }
                });
        }
    }
}
